<?php

namespace app\admin\controller;

use app\admin\service\AppVersionService;
use OSS\Core\OssException;
use OSS\OssClient;
use think\facade\Config;
use think\Request;

class AppVersion extends Backend
{
    /**
     * @var AppVersionService
     */
    protected $service;

    public function initialize()
    {
        parent::initialize();
        $this->service = new AppVersionService();
    }

    public function newest()
    {
        $this->jsonReturn(message('success', true, $this->service->newest()));
    }

    public function autoConfig()
    {
        $this->jsonReturn(message('success', true, $this->service->autoConfig()));
    }

    public function saveAutoConfig()
    {
        $data = request()->post();
        $this->jsonReturn(message('success', true, $this->service->saveAutoConfig($data)));
    }

    public function uploadApk(Request $request): void
    {
        $file = $request->file('file');
        if (!$file) {
            $this->jsonReturn(message('请选择apk文件', false));

            return;
        }
        if (env('apk_upload_type', 'oss') === 'oss') {
            $config = config()['oss']['apk'];
            try {
                $saveName = 'apk/' . uniqid() . '.' . pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);

                $ossClient = new OssClient($config['access_key'], $config['secret_key'], $config['end_point']);
                $res = $ossClient->uploadFile($config['bucket'], $saveName, $file->getRealPath());
                if (!empty($config['cnd'])) {
                    $path = trim($config['cnd'], '/') . '/' . $saveName;
                } else {
                    $path = str_replace('http', 'https', $res['oss-request-url']);
                }
            } catch (OssException $e) {
                $this->jsonReturn(message($e->getMessage(), false));

                return;
            }
        } else {
            $config = [
                'size' => 1024 * 1024 * 100,
                'ext'  => 'apk'
            ];
            $dir    = ATTACHMENT_PATH . '/apk';
            if (!file_exists($dir)) {
                mkdirs($dir, 0777, true);
            }
            $info = $file->validate($config)->move($dir);
            if (!$info) {
                $this->jsonReturn(message($file->getError(), false));

                return;
            }
            $path = url('/uploads/apk/' . $info->getSaveName(), '', false, true);
        }

        $this->jsonReturn(message('上传成功', true, $path));
    }
}